import React, { useState, useEffect } from "react";
import * as THREE from "three";
import { EffectComposer } from "three/addons/postprocessing/EffectComposer.js";
import { RenderPass } from "three/addons/postprocessing/RenderPass.js";
import { UnrealBloomPass } from "three/addons/postprocessing/UnrealBloomPass.js";
import { OutputPass } from "three/addons/postprocessing/OutputPass.js";
import App from "@/script/App";
import {
  objectMap,
  calculateMousePosition,
  createRaycaster,
  getIntersectedObject,
} from "./config";
import styled from "styled-components";

const ProvinceInfo = styled.div`
  position: absolute;
  width: 20px;
  height: 20px;
  z-index: 2;
  background: white;
  padding: 10px;
  visibility: hidden;
`;

let app: App;
let composer: EffectComposer;

function Map3D() {
  let lastRaf: any = -1;
  // 更新：根据按键进行移动
  let lastUpdateTime = 0;
  const maxFps = 30;
  let currentMeshMaterial: THREE.MeshStandardMaterial | null = null;
  const refThree = React.useRef<HTMLDivElement>(null!);
  const provinceInfo = React.useRef<HTMLDivElement>(null!);

  useEffect(() => {
    app = new App(refThree.current);
    app.addLight();
    app.scene.background = new THREE.Color(0x000000);

    const renderScene = new RenderPass(app.scene, app.camera);
    const bloomPass = new UnrealBloomPass(
      new THREE.Vector2(window.innerWidth, window.innerHeight),
      1.5,
      0.4,
      0.85
    );
    app.renderer.toneMappingExposure = 1.2;
    bloomPass.threshold = 0;
    bloomPass.strength = 0.2;
    bloomPass.radius = 0;
    const outputPass = new OutputPass();
    setTimeout(() => {
      app.scene.add(objectMap);

      composer = new EffectComposer(app.renderer);
      composer.addPass(renderScene);
      composer.addPass(bloomPass);
      composer.addPass(outputPass);
    }, 1000);
    animate();

    window.addEventListener("resize", onWindowResize);
    window.addEventListener("mousemove", onMouseMove, false);

    return () => {
      cancelAnimationFrame(lastRaf); // 清理渲染动画
      window.removeEventListener("resize", onWindowResize);
      window.removeEventListener("mousemove", onMouseMove, false);
      app.renderer.dispose();
    };
  }, []);

  function animate() {
    lastRaf = requestAnimationFrame(animate);
    app.renderer.render(app.scene, app.camera);
    app.orbitControls.update();
    if (composer) composer.render();
  }

  function onWindowResize() {
    app.camera.aspect = window.innerWidth / window.innerHeight;
    app.camera.updateProjectionMatrix();
    app.renderer.setSize(window.innerWidth, window.innerHeight);
  }

  function onMouseMove(event: MouseEvent) {
    // 节流阀
    if (Date.now() - lastUpdateTime < 1000 / maxFps) return;
    lastUpdateTime = Date.now();

    // 计算点击位置的二维向量
    let mousePosition = calculateMousePosition(event, refThree.current!);

    // 创建射线投射器
    let raycaster = createRaycaster(mousePosition, app.camera);

    // 检测射线与模型的交点
    let intersection = getIntersectedObject(raycaster, app.scene);

    if (intersection && intersection instanceof THREE.Mesh) {
      provinceInfo.current!.style.left = event.offsetX + 2 + "px";
      provinceInfo.current!.style.top = event.offsetY + 2 + "px";
      if (currentMeshMaterial) {
        currentMeshMaterial.color.set("#02A1E2");
        createProvinceInfo();
      }

      const materials = intersection.material as THREE.MeshStandardMaterial[];
      currentMeshMaterial = materials[0];
      materials[0].color.set(0xff0000);
    } else {
      if (currentMeshMaterial) {
        currentMeshMaterial.color.set("#02A1E2");
        currentMeshMaterial = null;
        // 0 ('#02A1E2'); 1('#3480C4');
      }
    }
  }

  function createProvinceInfo() {
    // 显示省份的信息
    // if ()
    //  provinceInfo.current.textContent = properties.name;
    //  provinceInfo.current.style.visibility = 'visible';
    // } else {
    //   provinceInfo.current.style.visibility = 'hidden';
    // }
  }

  return (
    <div
      id="container"
      ref={refThree}
      style={{ width: "100vw", height: "100vh" }}
    >
      <ProvinceInfo ref={provinceInfo}></ProvinceInfo>
    </div>
  );
}

export default Map3D;
